package com.canaan.business.controller.pc.bill;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import com.canaan.business.common.enums.inOutStock.ErpBillTypeEnum;
import com.canaan.business.common.enums.inOutStock.InOrderStatusEnum;
import com.canaan.business.common.enums.inOutStock.OutOrderStatusEnum;
import com.canaan.business.domain.bill.*;
import com.canaan.business.domain.inOutStock.OutStockBillDetail;
import com.canaan.business.domain.vo.OutStockQueryVo;
import com.canaan.business.domain.vo.OutStockResultVo;
import com.canaan.business.service.bill.IAdjustOutBillService;
import com.canaan.business.service.bill.IModulationOutBillDetailService;
import com.canaan.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.canaan.common.annotation.Log;
import com.canaan.common.core.controller.BaseController;
import com.canaan.common.core.domain.AjaxResult;
import com.canaan.common.enums.BusinessType;
import javax.annotation.Resource;

import com.canaan.business.service.bill.IModulationOutBillService;
import com.canaan.common.utils.poi.ExcelUtil;
import com.canaan.common.core.page.TableDataInfo;

/**
 * 出库调整单Controller
 *
 * @author canaan
 * @date 2025-03-24
 */
@Api(tags = "出库调整单")
@RestController
@RequestMapping("/bill/modulationOutBill")
public class ModulationOutBillController extends BaseController {
    @Resource
    private IModulationOutBillService modulationOutBillService;
    @Resource
    private IModulationOutBillDetailService modulationOutBillDetailService;
    @Resource
    private ISysConfigService sysConfigService;
    @Resource
    private IAdjustOutBillService adjustOutBillService;
    /**
     * 查询出库调整单列表
     */
    @ApiOperation(value = "查询出库调整单列表")
//    @PreAuthorize("@ss.hasPermi('bill:modulationOutBill:list')")
    @GetMapping("/list")
    public TableDataInfo list(ModulationOutBill modulationOutBill) {
        startPage();
        List<ModulationOutBill> list = modulationOutBillService.selectModulationOutBillList(modulationOutBill);
        return getDataTable(list);
    }

    /**
     * 导出出库调整单列表
     */
    @ApiOperation(value = "导出出库调整单列表")
    @PreAuthorize("@ss.hasPermi('bill:modulationOutBill:export')")
    @Log(title = "出库调整单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ModulationOutBill modulationOutBill) {
        List<ModulationOutBill> list = modulationOutBillService.selectModulationOutBillList(modulationOutBill);
        ExcelUtil<ModulationOutBill> util = new ExcelUtil<ModulationOutBill>(ModulationOutBill.class);
        util.exportExcel(response, list, "出库调整单数据");
    }

    /**
     * 获取出库调整单详细信息
     */
    @ApiOperation(value = "获取出库调整单详细信息")
//    @PreAuthorize("@ss.hasPermi('bill:modulationOutBill:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(modulationOutBillService.selectModulationOutBillById(id));
    }

    /**
     * 新增出库调整单
     */
    @ApiOperation(value = "新增出库调整单")
    @PreAuthorize("@ss.hasPermi('bill:modulationOutBill:add')")
    @Log(title = "出库调整单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ModulationOutBill modulationOutBill) {
        return toAjax(modulationOutBillService.insertModulationOutBill(modulationOutBill));
    }

    /**
     * 修改出库调整单
     */
    @ApiOperation(value = "修改出库调整单")
    @PreAuthorize("@ss.hasPermi('bill:modulationOutBill:edit')")
    @Log(title = "出库调整单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ModulationOutBill modulationOutBill) {
        return toAjax(modulationOutBillService.updateModulationOutBill(modulationOutBill));
    }
    @ApiOperation(value = "完成收货")
    @Log(title = "完成收货", businessType = BusinessType.UPDATE)
    @PostMapping("/complete")
    public AjaxResult complete(@RequestBody ModulationOutBill modulationOutBill){
        ModulationOutBill bill=modulationOutBillService.selectModulationOutBillByNo(modulationOutBill.getBizNo());
        if(bill==null){
            return error("出库调整单"+modulationOutBill.getBizNo()+"不存在");
        }
        bill.setStatus(InOrderStatusEnum.ACCOMPLISH.getCode());
        int result = modulationOutBillService.updateModulationOutBill(bill);
        return toAjax(result);
    }
    /**
     * 删除出库调整单
     */
    @ApiOperation(value = "删除出库调整单")
    @PreAuthorize("@ss.hasPermi('bill:modulationOutBill:remove')")
    @Log(title = "出库调整单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(modulationOutBillService.deleteModulationOutBillByIds(ids));
    }

    @ApiOperation(value = "调整出库执行")
    @Log(title = "调整出库执行", businessType = BusinessType.UPDATE)
    @PostMapping("/execute")
    @Transactional
    public AjaxResult execute(@RequestBody List<ModulationOutBill> outBills) {
        if (CollUtil.isEmpty(outBills)) {
            return error("调拨出库单数据为空");
        }
        for (ModulationOutBill item : outBills) {
            ModulationOutBill data = modulationOutBillService.selectModulationOutBillByNo(item.getBizNo());
            if (data == null) {
                return error("调拨出库单" + item.getBizNo() + "数据不存在");
            }
            if(OutOrderStatusEnum.NEW.getCode().equals(data.getStatus())) {
                modulationOutBillDispatcher(data);
            }
             else if(OutOrderStatusEnum.WAITING_PICK.getCode().equals(data.getStatus())){
                prePickOutBillDispatcher(data);
            }
        }
        return toAjax(1);
    }

    /**
     * 调拨出库单分配
     *
     * @param outBill 调拨出库单
     */
    private void modulationOutBillDispatcher(ModulationOutBill outBill) {
        //查询调拨出库单明细
        List<String> productNos = new ArrayList<>();
        List<Long> productCounts = new ArrayList<>();
        String stockStatus = outBill.getStockStatus();
        ModulationOutBillDetail query = new ModulationOutBillDetail();
        query.setBizNo(outBill.getBizNo());
        query.setDelFlag("0");
        List<ModulationOutBillDetail> details = modulationOutBillDetailService.selectModulationOutBillDetailList(query);
        for (ModulationOutBillDetail detail : details) {
            productNos.add(detail.getProductNo());
            productCounts.add(detail.getQty());
        }
        //OutStockQueryVo赋值
        OutStockQueryVo outStockQueryVo = new OutStockQueryVo();
        outStockQueryVo.setStockStatus(stockStatus);
        outStockQueryVo.setProductNos(productNos);
        outStockQueryVo.setProductCounts(productCounts);
        outStockQueryVo.setBillNo(outBill.getBizNo());
        outStockQueryVo.setBillType(ErpBillTypeEnum.MODULATION_OUT.getCode());
        outStockQueryVo.setCellCode(outBill.getCellCode());
        outStockQueryVo.setShortMatch(outBill.getShortMatch());
        OutStockResultVo outStockResultVo = adjustOutBillService.analyseOutStock(outStockQueryVo);
        if (CollUtil.isEmpty(outStockResultVo.getOutStockBillDetails())) {
            throw new RuntimeException("调拨出库单" + outBill.getBizNo() + "没有可调拨的库存");
        }
        for (ModulationOutBillDetail item : details) {
            List<OutStockBillDetail> outStockBillDetails = outStockResultVo.getOutStockBillDetails().stream().filter(O -> O.getProductNo().equals(item.getProductNo())).collect(Collectors.toList());
            if (outStockBillDetails.size() != 0) {
                OutStockBillDetail outStockBillDetail = outStockBillDetails.get(0);
                item.setBatchNo(outStockBillDetail.getBatchNo());
            }
        }
        modulationOutBillDetailService.batchUpdateModulationOutBillDetail(details);
        outBill.setStatus(OutOrderStatusEnum.PICKING.getCode());
        modulationOutBillService.updateModulationOutBill(outBill);
        adjustOutBillService.postOutStockCallback(outBill.getBizNo(),outBill.getStockStatus());
    }

    /**
     * 预选出库单分配
     */
    public void prePickOutBillDispatcher(ModulationOutBill modulationOutBill){
        ModulationOutBillDetail query = new ModulationOutBillDetail();
        query.setBizNo(modulationOutBill.getBizNo());
        query.setDelFlag("0");
        List<ModulationOutBillDetail> details = modulationOutBillDetailService.selectModulationOutBillDetailList(query);
        OutStockResultVo outStockResultVo= adjustOutBillService.handlePreOutStockBill(modulationOutBill.getBizNo(),ErpBillTypeEnum.MODULATION_OUT.getCode(),modulationOutBill.getAddress());
        for (ModulationOutBillDetail item : details) {
            List<OutStockBillDetail> outStockBillDetails = outStockResultVo.getOutStockBillDetails().stream().filter(O -> O.getProductNo().equals(item.getProductNo())).collect(Collectors.toList());
            if (outStockBillDetails.size() != 0) {
                OutStockBillDetail outStockBillDetail = outStockBillDetails.get(0);
                item.setBatchNo(outStockBillDetail.getBatchNo());
            }
        }
        modulationOutBillDetailService.batchUpdateModulationOutBillDetail(details);
        modulationOutBill.setStatus(OutOrderStatusEnum.PICKING.getCode());
        modulationOutBillService.updateModulationOutBill(modulationOutBill);
        adjustOutBillService.postOutStockCallback(modulationOutBill.getBizNo(), modulationOutBill.getStockStatus());
        logger.info("出库成功：{}", modulationOutBill);
    }


    /**
     * 订单打印
     */
    @ApiOperation(value = "订单打印")
    @Log(title = "订单打印", businessType = BusinessType.UPDATE)
    @GetMapping("/selectModulationOutBillForPrint")
    public AjaxResult selectModulationOutBillForPrint(@RequestParam("no") String no) {
        return success(modulationOutBillService.selectModulationOutBillForPrint(no));
    }
}
